package n13_reentrantlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author fu
 * @date 2022-01-10 20:46
 * 概要：
 * ----------------------------------------------------------------
 * |                                                              |
 * |               公平锁 ---   ReentrantLock 默认是不公平的        |
 * |       公平锁一般没有必要，会降低并发度，后面分析原理时会讲解       |
 * |=============================================================
 */
@Slf4j(topic = "c.T5")
public class T5 {

    public static void main(String[] args) throws InterruptedException {

        ReentrantLock lock = new ReentrantLock(true);
        log.debug("[主线程] 先抢到锁");
        // 1. [主线程] 先抢到锁
        lock.lock();

        // 2. 其他线程抢
        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    log.debug(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "t" + i).start();
        }

// 1s 之后去争抢锁
        // 3. 一秒后 [新线程] 抢锁
        Thread.sleep(1000);
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " start...");
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " running...");
            } finally {
                lock.unlock();
            }
        }, "强行插入").start();
        lock.unlock();

    }


}
